package com.match.competition_security.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.match.commonutils.Result;
import com.match.commonutils.ResponseUtil;
import com.match.competition_security.security.TokenManager;
import com.match.entity.loginEntity.LoginUser;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 * @author 芊薰
 */

public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;


    public TokenLoginFilter(){}

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/competition_role/login","POST"));
    }

    //根据用户名密码进行用户校验
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            //得到前端传过来的用户数据
            LoginUser user = new ObjectMapper().readValue(req.getInputStream(), LoginUser.class);
            //到service_role里UserDetailsServiceImpl进行用户查询
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getNumber(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录成功
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        if (user.getCurrentUserInfo().getRole().equals("教师")||user.getCurrentUserInfo().getRole().equals("学生")){
            ResponseUtil.out(res, Result.error("您没有登录权限，请联系管理员 ◔ ‸◔？"));
        }
        String token = tokenManager.createToken(user.getCurrentUserInfo().getNumber());
        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getNumber(), user.getPermissionValueList());
        ResponseUtil.out(res, Result.ok().data("token", token));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, Result.error("请检查您输入的用户名或密码"));
    }
}
